<?php
/**
 * Application Utilities.
 *  
 * @author Nguyen Hai Ha
 * @version 1.0
 */

class Utilities{
	function cv2urltitle($text) {
	
		$text = str_replace(
		array(' ','%',"/","\\",'"','?','<','>',"#","^","`","'","=","!",":" ,",,","..","*","&","__","▄"),
		array('-','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-','' ,'-','' ,'' ,'' , "_" ,"" ,""),
		$text);
		
		$text = str_replace(
		array('_quot;', '”', '“', ',', '.'), 
		array('', '', '', '', ''), 
		$text);
		
		$chars = array("a","A","e","E","o","O","u","U","i","I","d", "D","y","Y");
		
		$uni[0] = array("á","à","ạ","ả","ã","â","ấ","ầ", "ậ","ẩ","ẫ","ă","ắ","ằ","ặ","ẳ","� �");
		$uni[1] = array("Á","À","Ạ","Ả","Ã","Â","Ấ","Ầ", "Ậ","Ẩ","Ẫ","Ă","Ắ","Ằ","Ặ","Ẳ","� �");
		$uni[2] = array("é","è","ẹ","ẻ","ẽ","ê","ế","ề" ,"ệ","ể","ễ");
		$uni[3] = array("É","È","Ẹ","Ẻ","Ẽ","Ê","Ế","Ề" ,"Ệ","Ể","Ễ");
		$uni[4] = array("ó","ò","ọ","ỏ","õ","ô","ố","ồ", "ộ","ổ","ỗ","ơ","ớ","ờ","ợ","ở","� �");
		$uni[5] = array("Ó","Ò","Ọ","Ỏ","Õ","Ô","Ố","Ồ", "Ộ","Ổ","Ỗ","Ơ","Ớ","Ờ","Ợ","Ở","� �");
		$uni[6] = array("ú","ù","ụ","ủ","ũ","ư","ứ","ừ", "ự","ử","ữ");
		$uni[7] = array("Ú","Ù","Ụ","Ủ","Ũ","Ư","Ứ","Ừ", "Ự","Ử","Ữ");
		$uni[8] = array("í","ì","ị","ỉ","ĩ");
		$uni[9] = array("Í","Ì","Ị","Ỉ","Ĩ");
		$uni[10] = array("đ");
		$uni[11] = array("Đ");
		$uni[12] = array("ý","ỳ","ỵ","ỷ","ỹ");
		$uni[13] = array("Ý","Ỳ","Ỵ","Ỷ","Ỹ");
		
		for($i=0; $i<=13; $i++) {
		$text = str_replace($uni[$i],$chars[$i],$text);
		}
	
		return $text;
	}
	
	public function htmlFilter($text) {
		$text = str_replace(
		array(' ','%',"/","\\",'"','?','<','>',"#","^","`","'","!" ,",,","..","*","&","__","▄"),
		array(' ','' ,'' ,''  ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,''  ,'' ,'' ,'' , "_" ,"" ,""),
		$text);
		
		$text = str_replace(
		array('_quot;', '”', '“', ',', '.'), 
		array('', '', '', '', ''), 
		$text);
		
		return $text;
	}
	
	/**
	 * Get cities
	 */
	public function getCity($language='vn'){
		$cities_config = new Zend_Config_Xml ( './app/configs/cities.xml', $language );
		$cities = $cities_config->cities->city->toArray ();
		return $cities;
	}
	
	/**
	 * utilities cut string.
	 * param: $string, $string_leng.
	 * return substring with lenght = $string_leng.
	 */
	public function substring($string="", $string_leng=500){
		if(strlen($string) > $string_leng){
			$string = substr($string, 0, $string_leng);
			$space = strripos($string, " ");
			$string = substr($string, 0, $space )." ... ";
		}
		return $string;
	}
	/**
	 * Param: mail address.
	 * Return: true, or false.
	 */
	public function checkemail($email=""){
		$e = "/^[-+\\.0-9=a-z_]+@([-0-9a-z]+\\.)+([0-9a-z]){2,3}$/i";
		if(!preg_match($e, trim($email))) {
			return false;
		}else{
			return true;
		}
	}
	
	public function check_mobile($mobile=""){
		$e = "/^([0-9]){9,12}$/";
		if(!preg_match($e, trim($mobile))) {
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * Param: dd/mm/yyyy
	 * Return: yyyy/dd/mm
	 */
	public function formatDateToDatabase($date='01/01/1970'){
		$time = split("/", $date);
		if (strlen($time[2] > 3)){
			return $time[2]."/".$time[0]."/".$time[1];
		}
		else return $date;
	}
	
	/**
	 * utilitys format date.
	 * param: $timestamp.
	 * return: date with format mm-dd-YYYY.
	 */
	public function formatdate($timestamp, $flag=0){		
		$time = date_parse($timestamp);	
		if ($time['month']){
			$month = strlen($time['month'])<2 ? "0".$time['month']: $time['month'];
			$day = strlen($time['day'])<2 ? "0".$time['day']: $time['day'];
			if ($flag != 0){
				return $day."/".$month."/".$time['year'];
			}else{
				return $day."-".$month."-".$time['year'];
			}
		}else{
			return "";
		}
	}

	function uploadImage( $images, $folder, $old_image="" ){
		//define a maxim size for the uploaded images
		define ("MAX_SIZE", Constant::IMAGE_MAX_SIZE);
		// define the width and height for the thumbnail
		// note that theese dimmensions are considered the maximum dimmension and are not fixed,
		// because we have to keep the image ratio intact or it will be deformed
		define ("WIDTH", Constant::IMAGE_WIDTH);
		//Hien tai bien nay chua duoc dung.
		//Bien nay se duoc dung neu muon copy anh voi ty le thay doi cho ca width va height.
		define ("HEIGHT", Constant::IMAGE_HEIGHT);
		//Begin: Upload and copy new thumbnai images.
		//Ham nay chi dung duoc voi anh co duoi .jpg, jpeg, png.
		$afolder = $folder."temp/";
		$thumb_folder = $folder ;				     
		$image=$images['name'];
		if ($image){            
			$filename = stripslashes($images['name']);
			$extension = $this->getExtension($filename);
			$extension = strtolower($extension);            
			if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")){
			?>
				<script language="javascript">
					alert("<?php echo "File type is not image format!";?>");
					window.history.back();
				</script>
			<?php
				die;		               
			}else{                
				$sizekb=filesize($images['tmp_name']);
				if ($sizekb < MAX_SIZE*1024){				                    
					$image_name = md5($filename) . time() . '.' . $extension;                
					$newname = $afolder . $image_name;
					$copied = copy($images['tmp_name'], $newname);                
					if ($copied){
					    $thumb_name=$thumb_folder.$image_name;                         
					    $this->make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
					}
				}
			} 
			// Delete image in temp folder.
			if (isset($newname))unlink($newname);			
		}    
		//End: Upload and copy images.
		// If user upload new photo. Delete old image.
		if (isset($image_name)){
			unlink($thumb_folder.$old_image);
		}
		if (isset($image_name)) return $image_name;
		else return $old_image;
		
	}// End function.
	
	
	//Begin: Ham tao thumbnai images.
	//Dung tao them 1 anh thumbnai trong khi nhap tin cua CMS.
	//Anh thumbnai nay se duoc dung de hien thi cung voi mo ta cua tin.
	//Hien tai ham nay dang duoc dung de tao anh co kich thuoc : chieu rong theo kich thuoc duoc fix cung.
	//chieu cao se thu lai theo ty le tinh duoc cua chieu rong.
	//Neu muon thu anh theo ty le cua ca 2 chieu, mo comment tren ung voi "$ratio2" va cac dong code lien quan.
	//this is the function that will create the thumbnail image from the uploaded image
	//the resize will be done considering the width and height defined, but without deforming the image
	public function make_thumb($img_name,$filename,$new_w="150",$new_h="150"){
	    //get image extension.
	    $ext=$this->getExtension($img_name);
	    //creates the new image using the appropriate function from gd library
	    if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
	    $src_img=imagecreatefromjpeg($img_name);
	
	    if(!strcmp("png",$ext))
	    $src_img=imagecreatefrompng($img_name);
		
	    if(!strcmp("gif",$ext))
	    $src_img=imagecreatefromgif($img_name);
	    
	    //gets the dimmensions of the image
	    $old_x=imageSX($src_img);
	    $old_y=imageSY($src_img);
	
	    // next we will calculate the new dimmensions for the thumbnail image
	    // the next steps will be taken:
	    // 1. calculate the ratio by dividing the old dimmensions with the new ones
	    // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
	    // and the height will be calculated so the image ratio will not change
	    // 3. otherwise we will use the height ratio for the image
	    // as a result, only one of the dimmensions will be from the fixed ones
	    $ratio1=$old_x/$new_w;
	//    $ratio2=$old_y/$new_h;
	//    if($ratio1>$ratio2) {
	        $thumb_w=$new_w;
	        $thumb_h=$old_y/$ratio1;
	//    }else {
	//        $thumb_h=$new_h;
	//        $thumb_w=$old_x/$ratio2;
	//    }
	
	    // we create a new image with the new dimmensions
	    $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	
	    // resize the big image to the new created one
	    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
	
	    // output the created image to the file. Now we will have the thumbnail into the file named by $filename
	    if(!strcmp("png",$ext)){
	    	imagepng($dst_img,$filename);
	    }elseif(!strcmp("gif",$ext)){
	    	imagegif($dst_img,$filename);
	    }else{
	    	imagejpeg($dst_img,$filename);
	    }
	    //destroys source and destination images.
	    imagedestroy($dst_img);
	    imagedestroy($src_img);
	}
	
	// This function reads the extension of the file.
	// It is used to determine if the file is an image by checking the extension.
	public function getExtension($str) {
	    $i = strrpos($str,".");
	    if (!$i) { return ""; }
	    $l = strlen($str) - $i;
	    $ext = substr($str,$i+1,$l);
	    return $ext;
	}
	//End: Ham tao anh.
   
	
//	#function convert to viet nam
//	function CovertVn($str)
//	{
//		$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|� �|ặ|ẳ|ẵ)/", 'a', $str);
//		$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
//		$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
//		$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|� �|ợ|ở|ỡ)/", 'o', $str);
//		$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
//		$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
//		$str = preg_replace("/(đ)/", 'd', $str);
//		$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|� �|Ặ|Ẳ|Ẵ)/", 'A', $str);
//		$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
//		$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
//		$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|� �|Ợ|Ở|Ỡ)/", 'O', $str);
//		$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
//		$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
//		$str = preg_replace("/(Đ)/", 'D', $str);
//		$str = preg_replace("/( )/", '-', $str);		
//		return $str;
//	}
}